<template>
	<view class="page-container">
		<view class="main-1">
			<u--form labelPosition="top">
			<!-- 	<u-form-item prop="fileList1" ref="item1">
					<view class="avatar-1">
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="1" :previewFullImage="true" width="218rpx" height="218rpx"
							@chooseImage="chooseImage"></u-upload>
					</view>
				</u-form-item> -->
				<u-form-item prop="share.nickName" ref="item1">
					<u--input v-model="nickName" placeholder="请输入微信名称" border="bottom" fontSize="16px"></u--input>
				</u-form-item>
				<!-- <u-form-item prop="share.phone" ref="item1">
					<u--input v-model="phone" placeholder="请输入手机号" border="bottom" fontSize="16px"></u--input>
				</u-form-item> -->
			</u--form>
			<u-button class="form-1" type="primary" style="width: 40%;" @click="handleSubmit">确认修改</u-button>
		</view>

	</view>
</template>

<script>
	import request from '@/util/request'
	export default {
		data() {
			return {
				fileList1: [],
				nickName: '',
				phone: '',
				originalPhone: '',//保存原始手机号
				userId: '',
				images: [],
				deviceId: 0,
				originalAvatarUrl: '', // 保存原始头像路径
				loginUser:{}
			};
		},
		onLoad() {
			// 获取设备信息
			this.deviceId = uni.getSystemInfoSync().deviceId;
			//回显
			this.byUserID();
		},
		methods: {
			async uploadNewImages() {
				const uploadResults = await Promise.all(this.fileList1.map(file => this.uploadFilePromise(file.url)));
				this.images = uploadResults; // 保存所有上传后的图片地址
			},
			async checkPhoneExist(phone) {
				try {
					const response = await request({
						url: '/users/checkPhoneExist',
						method: 'get',
						data: {
							phone: phone
						}
					});
					if (response.data.phone.length) {
						return true; // 返回 true 表示手机号存在
					}
					return false; // 返回 false 表示手机号不存在
				} catch (error) {}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			afterRead(event) {
				debugger
				let lists = [].concat(event.file);
				console.log("list+++"+JSON.stringify(lists))
				lists.forEach(item => {
					this.fileList1.push(item);
				});
				// 如果有新图片，则上传，否则保持原图片
				if (lists.length > 0) {
					this.uploadFilePromise(this.fileList1[0].url)
				}
			},
			// 使用相机拍照
			chooseImage() {
				uni.chooseImage({
					count: 1 - this.fileList1.length, // 剩余可选择的图片数
					sourceType: ['camera'], // 只允许使用相机
					success: (res) => {
						this.fileList1 = this.fileList1.concat(res.tempFiles);
					}
				});
			},
			async handleSubmit() {
				// if (this.fileList1.length === 0) {
				// 	uni.showToast({
				// 		title: '请至少上传一张图片',
				// 		icon: 'none',
				// 		duration: 2000
				// 	});
				// 	return; // 如果没有上传图片，则退出方法
				// }
				// 手机号格式校验
				// 如果用户输入了手机号，则进行格式校验
				if (this.phone) {
					if (!/^1[3-9]\d{9}$/.test(this.phone)) {
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none',
							duration: 2000
						});
						return; // 手机号格式不正确，则退出方法
					}
				}
				if (this.phone) {
					if (this.phone !== this.originalPhone) {
						// 手机号唯一性检查
						const isPhoneExist = await this.checkPhoneExist(this.phone);
						if (isPhoneExist) {
							uni.showToast({
								title: '手机号已存在',
								icon: 'none',
								duration: 2000
							});
							return; // 如果手机号已存在，则不发送请求
						}
					}
				}
				// 发送请求
				try {
					const avatarUrl = this.images.length > 0 ? this.images.join(',') : this.originalAvatarUrl;
					const response = await request({
						url: '/users/update',
						method: 'post',
						data: {
							avatarUrl: avatarUrl, // 使用新的或原有的头像路径
							nickName: this.nickName,
							userId: this.deviceId,
							phone: this.phone,
						}
					});
					this.loginUser.avatarUrl = avatarUrl
					this.loginUser.phone =  this.phone
					this.loginUser.nickName =  this.nickName
					uni.setStorageSync("loginUser",this.loginUser)
					uni.showToast({
						title: '修改成功',
						icon: 'success',
						duration: 2000 // 持续时间，单位为毫秒
					});
					uni.reLaunch({
						url: "/pages/my/index"
					});
				} catch (err) {
					uni.showToast({
						title: '提交失败',
						icon: 'none',
						duration: 2000
					});
				}
			},
			uploadFilePromise(url) {
				const urls = this.$baseUrl + "/common/upload";
				uni.uploadFile({
					url: urls, // 图片上传接口
					filePath: url,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: (res) => {
						const imgUrls = JSON.parse(res.data).fileName;
						this.images[0] = imgUrls // 返回上传后的图片地址
					}
				});
			},

			getoriginalPhone() {
				request({
					url: '/users/getUserById',
					method: 'get',
					data: {
						userId: this.deviceId
					}
				}).then(res => {
					this.originalPhone = res.data.phone; // 存储原始手机号
				})
			},

			byUserID() {
				this.loginUser =  uni.getStorageSync("loginUser")
				this.nickName = this.loginUser.nickName;
				this.phone = this.loginUser.phone;
				this.originalAvatarUrl = this.loginUser.avatarUrl; // 初始化原始头像路径
				this.originalPhone = this.loginUser.phone; // 存储原始手机号
				if(this.loginUser.avatarUrl){
					const url = this.$baseUrl + this.loginUser.avatarUrl;
					this.fileList1 = [{
						url: url,
					}]
				}
				// request({
				// 		url: '/users/getUserById',
				// 		method: 'get',
				// 		data: {
				// 			userId: this.deviceId
				// 		}
				// 	}).then(res => {
				// 		this.nickName = res.data.nickName;
				// 		this.phone = res.data.phone;
				// 		this.originalAvatarUrl = res.data.avatarUrl; // 初始化原始头像路径
				// 		this.originalPhone = res.data.phone; // 存储原始手机号
				// 		const url = this.$baseUrl + res.data.avatarUrl;
				// 		this.fileList1 = [{
				// 			url: url,
				// 		}]
				// 	})
				// 	.catch(err => {})
			},
		}
	};
</script>

<style scoped>
	/* 设置页面容器为全屏并设置白色背景 */
	.page-container {
		width: 100%;
		height: 100vh;
		/* 100vh 表示视窗的高度 */
		background-color: white;
		/* 设置背景色为白色 */
		display: flex;
		flex-direction: column;
	}

	/* 头像div */
	.avatar-1 {
		width: 218rpx;
		height: 218rpx;
		margin: auto;
	}

	/* 整体大小 */
	.main-1 {
		flex: 1;
		/* 让主内容区占满剩余空间 */
		padding: 5%;
		/* 适当的内边距 */
	}

	/* 发布按钮边距 */
	.u-button {
		/* margin: 0rpx 0rpx 20% 0rpx; */
		/* 上 右 下 左 */
		font-size: 15px;
		/* 调整字体大小 */
	}

	/* 间隔 */
	::v-deep .u-form-item.data-v-5e7216f1 {
		display: flex;
		flex-direction: column;
		font-size: 16px;
		color: #303133;
		margin-bottom: 10%;
	}


	/* 标题:字体大小 */
	::v-deep .u-form-item__body__left__content__label.data-v-5e7216f1 {
		display: flex;
		flex-direction: row;
		align-items: center;
		flex: 1;
		color: #303133;
		font-size: 13px;
	}

	/* 发布按钮大小 字体大小 */
	::v-deep .u-button.data-v-3bf2dba7 {
		width: 200rpx;
		font-size: 12px;
		background-color: rgb(7, 193, 96);
		border: 0;
	}
</style>